package com.xxx.car.web.admin;

import com.xxx.car.cache.CarRedisTemplate;
import com.xxx.car.constants.RedisConstants;
import com.xxx.car.entity.vo.request.ReqPushMsgSend;
import com.xxx.common.base.enums.AdminErrorEnum;
import com.xxx.common.base.vo.AdminResponse;
import com.xxx.common.push.exception.PushException;
import com.xxx.common.push.msg.MsgPayload;
import com.xxx.common.push.umeng.UmengPush;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by wenjiexu on 2017/7/5.
 */
@Controller
@RequestMapping("/admin/push")
public class AdminPushController {

    @Autowired
    private CarRedisTemplate carRedisTemplate;

    @Autowired
    private UmengPush umengPush;

    @RequestMapping("/")
    public String index() {
        return "push";
    }

    @RequestMapping("/send")
    @ResponseBody
    public AdminResponse send(@Valid @ModelAttribute ReqPushMsgSend reqPushMsgSend, BindingResult bindingResult) throws IOException {
        if (bindingResult.hasErrors()) {
            return AdminResponse.returnFail(AdminErrorEnum.PARAMETER_INVALID);
        }
        List<String> userIds = reqPushMsgSend.getUserIds();
        List<String> deviceTokens = new ArrayList<>();
        if (userIds != null) {
            userIds.stream().forEach(e->{
                String deviceToken = (String) carRedisTemplate.get(RedisConstants.USER_DEVICE_TOKEN + e);
                deviceTokens.add(deviceToken);
            });
        }
        MsgPayload payload = new MsgPayload();
        payload.setTitle("高速助手");
        payload.setTicker(reqPushMsgSend.getMsg());
        payload.setText(reqPushMsgSend.getMsg());
        try {
            umengPush.push(payload, deviceTokens);
        } catch (PushException e) {
            return AdminResponse.returnFail(e.getMessage());
        }
        return AdminResponse.returnSuccess();
    }
}
